#nullable enable
using Godot;
using AndroidUnevenRoadGame.Game;

namespace AndroidUnevenRoadGame.UI
{
    public partial class EventScene : Control
    {
        [Export] private Label? _titleLabel;
        [Export] private RichTextLabel? _descriptionLabel;
        [Export] private VBoxContainer? _optionsContainer;
        [Export] private Button? _leaveButton;

        public override void _Ready()
        {
            _titleLabel ??= GetNode<Label>("Panel/VBox/Title");
            _descriptionLabel ??= GetNode<RichTextLabel>("Panel/VBox/Description");
            _optionsContainer ??= GetNode<VBoxContainer>("Panel/VBox/OptionsContainer");
            _leaveButton ??= GetNode<Button>("Panel/VBox/LeaveButton");

            _leaveButton!.Pressed += OnLeavePressed;

            var game = GameRoot.Instance;
            game.StateChanged += OnStateChanged;

            RenderEvent(game.EventManager.CurrentEvent ?? game.EventManager.GenerateRandomEvent());
        }

        public override void _ExitTree()
        {
            if (!Engine.IsEditorHint() && GameRoot.Instance != null)
            {
                GameRoot.Instance.StateChanged -= OnStateChanged;
            }
        }

        private void OnLeavePressed()
        {
            var game = GameRoot.Instance;
            game.AdvanceFloor();
            game.ChangeState(GameRoot.GameState.Map);
        }

        private void OnStateChanged(int stateValue)
        {
            var state = (GameRoot.GameState)stateValue;
            Visible = state == GameRoot.GameState.Event;
            if (Visible)
            {
                var game = GameRoot.Instance;
                RenderEvent(game.EventManager.CurrentEvent ?? game.EventManager.GenerateRandomEvent());
            }
        }

        private void RenderEvent(EventDefinition definition)
        {
            if (_titleLabel != null)
            {
                _titleLabel.Text = definition.Title;
            }

            if (_descriptionLabel != null)
            {
                _descriptionLabel.Text = definition.Description;
            }

            if (_optionsContainer == null)
            {
                return;
            }

            foreach (var child in _optionsContainer.GetChildren())
            {
                child.QueueFree();
            }

            foreach (var option in definition.Options)
            {
                var button = new Button
                {
                    Text = option.Description,
                    SizeFlagsHorizontal = SizeFlags.ExpandFill
                };

                button.Pressed += () =>
                {
                    GameRoot.Instance.EventManager.ApplyEventOption(definition, option);
                    GameRoot.Instance.AdvanceFloor();
                    GameRoot.Instance.ChangeState(GameRoot.GameState.Map);
                };

                _optionsContainer.AddChild(button);
            }
        }
    }
}

